import { _decorator, Component, instantiate, Vec3, Node, tween, Animation, Material, ModelComponent, EventTarget} from 'cc';
import {SimpleCard} from './SimpleCard';
import Util from './Util';
import { ResourceManager } from './ResourceManager';
import { Layer } from "./StaticDefine";
import { GameManager } from "./GameManager";

enum ModleType {
    BACK = 0,
    FACE = 1,
    HAND = 2,
    TOUCH = 3,
}

const { ccclass, property } = _decorator;
@ccclass('Card') // 用 @ccclass 声明类为 Cocos 组件
export class Card extends SimpleCard {

    private modleType: ModleType = ModleType.BACK;

    public touchCard: boolean = false;
    public handCard: boolean = true;

    public cardID: number = 0;
    private cardName: string = '';

    private matrix!: Node;
    private model: Node | null = null;

    onMyEvent(data: any) {
        // console.log('Received event data:', data);
        // 处理事件数据
        if(Math.floor( this.cardID / 10 ) == Math.floor( data / 10 ))
        {
            this.setSelected(true);
        }
        else
        {
            this.setSelected(false);
        }
    }

    // 触发事件
    emitMyEvent(data: any) {
        GameManager.instance.getEvent().emit('SelectCard', data);
    }

    onDestroy() {
        // 移除消息监听
        GameManager.instance.getEvent().off('SelectCard', this.onMyEvent, this);
    }

    onLoad() {
        super.onLoad();//for layer

        GameManager.instance.getEvent().on('SelectCard', this.onMyEvent, this);

        const baseNode = this.node.getChildByName('Matrix');
        if(baseNode)
        {
            this.matrix = baseNode;
        }
        // console.log("this.cardID", this.cardID);
        if(this.cardID == 0)
        {
            this.cardID = Util.randomCardID();
        }
        
        this.setModel();
        this.setShadow();
        this.setKing();

        // console.log("onLoad card~~~~");
    }

    setCardID(cardID:number)
    {
        this.cardID = cardID;
    }

    setModel() {
        const model = ResourceManager.getNewCard(this.cardID);
        if(model)
        {
            model.layer = this.node.layer;
            const modelContainer = this.matrix.getChildByName('Model');
            modelContainer?.addChild(model);

            const modelComponent = model.getComponent(ModelComponent);
            if(modelComponent)
            {
                if(this.modleType == ModleType.BACK)
                {
                    modelComponent.material = ResourceManager.getBaseCardMat();
                }
                else if(this.modleType == ModleType.FACE || this.modleType == ModleType.HAND)
                {
                    modelComponent.material = ResourceManager.getHandCardMat();
                }
                else if(this.modleType == ModleType.TOUCH)
                {
                    modelComponent.material = ResourceManager.getTouchCardMat();
                }
            }

            this.model = model;
        }

    }

    setShadow() {
        if(this.modleType == ModleType.BACK || this.modleType == ModleType.FACE)
        {
            const shadow = this.node.getChildByName('ShadowH');
            if(shadow)
            {
                shadow.active = true;
            }
        }
        else if(this.modleType == ModleType.HAND)
        {
            const shadow = this.node.getChildByName('Shadow');
            if(shadow)
            {
                shadow.active = true;
            }
        }
    }

    setDisable() {
        const model = this.model;
        if(model)
        {
            const modelComponent = model.getComponent(ModelComponent);
            if(modelComponent)
            {
                modelComponent.material = ResourceManager.getBlackCardMat();
            }
        }
        
        // this.syncLayer();
    }

    setSelected(selected: boolean = false) {
        if(this.modleType == ModleType.FACE )
        {
            const model = this.model;
            if(model)
            {
                const modelComponent = model.getComponent(ModelComponent);
                if(modelComponent)
                {
                    if(selected)
                    {
                        modelComponent.material = ResourceManager.getSelectdCardMat();
                    }
                    else
                    {
                        modelComponent.material = ResourceManager.getHandCardMat();
                    }
                }
            }
        }
    }

    setKing() {
        if(this.model == null)
            return;

        if(this.modleType == ModleType.FACE || this.modleType == ModleType.TOUCH )
        {

            const cardValue = Math.floor(this.cardID / 10) % 10;
            if(cardValue == 1 || cardValue == 2 )
            {
                const modelComponent = this.model.getComponent(ModelComponent);
                if(modelComponent)
                {
                    modelComponent.material = ResourceManager.getKingCardMat();
                }
                const baseNode = this.node.getChildByName('Matrix');
                if(baseNode)
                {
                    const model = baseNode.getChildByName('Model');
                    if(model)
                    {
                        const cover = model.getChildByName('Cover');
                        if(cover)
                        {
                            cover.active = true;
                        }
                    }
                }
            }
        }
    }

    setArrow(direction:number) {
        // if(this.modleType == ModleType.FACE )
        {
            const baseNode = this.node.getChildByName('Matrix');
            if(baseNode)
            {
                const model = baseNode.getChildByName('Model');
                if(model)
                {
                    const cover = model.getChildByName('Cover2');
                    if(cover)
                    {
                        cover.active = true;
                        cover.eulerAngles = new Vec3(0, 0, 90 * direction);
                    }
                }
            }
        }
    }


    setBaseCard(bOpen: boolean = false) {
        const baseNode = this.node.getChildByName('Matrix');
        if(baseNode)
        {
            if(bOpen)
            {
                baseNode.eulerAngles = new Vec3(0, 0, 0);
            }
            else
            {
                baseNode.eulerAngles = new Vec3(180, 0, 0);
            }
        }

        this.node.eulerAngles = new Vec3(-90, 0, 0);

        if(bOpen)
        {
            this.modleType = ModleType.FACE;
        }
        else
        {
            this.modleType = ModleType.BACK;
        }
    }

    setHandCard(bTouch: boolean = false) {
        if(bTouch)
        {
            this.modleType = ModleType.TOUCH;
        }
        else
        {
            this.modleType = ModleType.HAND;
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    openCard(callback: Function | null = null){

        const model = this.matrix.getChildByName('Model');
        if(model == null)
            return;

        // console.log('openCard...');
        const matrix = this.matrix;
        matrix.position = new Vec3(0, -0.022, 0.012);
        matrix.eulerAngles = new Vec3(90, 0, 0); // 初始角度
        model.position = new Vec3(0, 0.022, -0.012);

        const shadow = this.node.getChildByName('Shadow');
        if(shadow)
        {
            shadow.position = new Vec3(0, -0.1, 0);
        }

        const animation = this.getComponent(Animation);
        animation?.play("OpenCard");
        animation?.once(Animation.EventType.FINISHED, () => {
            if(callback)
                {
                    callback();
                }
        });

        return;

        // tween(matrix)
        // .to(0.3, { eulerAngles: new Vec3(0, 0, 0) }) // 翻转动画
        // .call(() => {
        //     matrix.position = new Vec3(0, 0, 0);
        //     model.position = new Vec3(0, 0, 0);
        //     if(callback)
        //     {
        //         callback();
        //     }
        // })
        // .start();
    }

    closeCard(callback: Function | null = null) {
        
        const model = this.matrix.getChildByName('Model');
        if(model == null)
            return;
        
        const matrix = this.matrix;
        matrix.position = new Vec3(0, -0.022, 0.012);
        matrix.eulerAngles = new Vec3(0, 0, 0); // 初始角度

        model.position = new Vec3(0, 0.022, -0.012);
        
        const animation = this.getComponent(Animation);
        animation?.play("CloseCard");
        animation?.once(Animation.EventType.FINISHED, () => {
            if(callback)
            {
                callback();
            }
        });

        return;

        // tween(matrix)
        // .to(0.3, { eulerAngles: new Vec3(-90, -90, -90) }) // 翻转动画
        // .call(() => {
        //     if(callback)
        //     {
        //         callback();
        //     }
        // })
        // .start();
    }

    showCard(callback: Function | null = null) {
        const matrix = this.matrix;
        matrix.eulerAngles = new Vec3(0, 0, 0); // 初始角度
        const pos = matrix.position;

        const animation = this.getComponent(Animation);
        animation?.play("ShowCard");
        animation?.once(Animation.EventType.FINISHED, () => {
            if(callback)
                {
                    callback();
                }
        });

        return;

        tween(matrix)
        .to(0.3, { 
            eulerAngles: new Vec3(90, 0, 0), // 翻转动画
            position: new Vec3(pos.x, -0.01, pos.z) // 设置新的位置
        })
        .call(() => {
            if(callback)
            {
                callback();
            }
        })
        .start();
    }

    liftCard(callback: Function | null = null){

        const model = this.node;
        if(model == null)
            return;
        // console.log('openCard...');
        const matrix = this.matrix;
        let angle = matrix.eulerAngles;
        const liftAngle = new Vec3(angle.x, angle.y, 30);

        let pos = matrix.position;
        const liftPos = new Vec3(pos.x, 0.04, pos.z);

        tween(matrix)
        .to(0.2, { 
            eulerAngles: liftAngle ,
            position: liftPos
        }) // 翻转动画
        .call(() => {
            if(callback)
            {
                callback();
            }
        })
        .start();
    }

    dropCard(callback: Function | null = null){

        const model = this.node;
        if(model == null)
            return;
        // console.log('openCard...');
        const matrix = this.matrix;
        let angle = matrix.eulerAngles;
        const liftAngle = new Vec3(angle.x, angle.y, 0);

        let pos = matrix.position;
        const liftPos = new Vec3(pos.x, 0, pos.z);

        tween(matrix)
        .to(0.2, { 
            eulerAngles: liftAngle ,
            position: liftPos
        }) // 翻转动画
        .call(() => {
            if(callback)
            {
                callback();
            }
        })
        .start();
    }
    
    setMode(rotate: boolean) {
        const mjp = this.node.getChildByName(this.cardName);
        console.log("cardName", this.cardName);
        console.log("mjp", mjp);
        
        const staticModel = this.node.getChildByName(this.cardName)?.getChildByName('static');
        const rotateModel = this.node.getChildByName(this.cardName)?.getChildByName('rotate');
        if(staticModel && rotateModel)
        {
            console.log("setMode...in");
            if(rotate)
            {
                staticModel.active = false;
                rotateModel.active = true;
            }
            else
            {
                staticModel.active = true;
                rotateModel.active = false;
            }
        }
        else
        {
            console.log("setMode...error");
        }
    }

}